import Sports
import requests as req
import hashlib
import json
import fuckv1
import fuckv2
import Database
import TrajectoryV1
import NanjubeizhiV1
import logging
import os
import time
database=Database.database()
LOGPATH = "logs/"
DATAMODEL = 3  # 0: fuckv1 1: fuckv2 2: TrajectoryV1 3: NanjubeizhiV1

class User:
    
    xh=""
    token=""
    id=""
    header={}
    device="iPhone 16 Pro Max"
    file_handler = ""  # 设置日志文件编码为UTF-8
    def __init__(self,xh):
        self.xh=xh
        self.header["User-Agent"]="Mozilla/5.0 (Linux; Android 13; 22011211C Build/TP1A.220624.014; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/112.0.5615.48 Mobile Safari/537.36"
        self.initLogger()
        
    def initLogger(self):
        logformat='%(asctime)s %(levelname)s: %(message)s'
        os.makedirs(LOGPATH+self.xh, exist_ok=True)
        logging.basicConfig(filename=LOGPATH+self.xh+"/"+'User.log', level=logging.DEBUG,
                    format=logformat, encoding='utf-8')
        self.file_handler = logging.FileHandler(LOGPATH+self.xh+"/"+'User.log', encoding='utf-8') 
        self.file_handler.setLevel(logging.DEBUG)  # 设置文件日志级别
        file_formatter = logging.Formatter(logformat)
        self.file_handler.setFormatter(file_formatter)
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)  # 设置控制台日志级别
        console_formatter = logging.Formatter(logformat)
        console_handler.setFormatter(console_formatter)
        root_logger = logging.getLogger()
        root_logger.addHandler(self.file_handler)

    def security_check(self):
        logging.info("正在执行安全检查")
        userInfo=self._getUserInfo(self.xh)
        logging.debug(userInfo)
        if(self.IfLoginInOtherdevice(userInfo)==True):
            logging.info("当前账号已登录其他设备，设备校验通过！")
        else:
            logging.critical("错误！请先在其他设备上登录该账号后重试！")
            return True
        url="http://aitiyuplus.cn:8091/sports-reform/AddUserController/findNum?userId=7f181227-a8c0-4520-bc2d-99f5c636494c&clubId=null"
        url=url.replace("7f181227-a8c0-4520-bc2d-99f5c636494c",self.id)
        req.get(url=url,headers=self.header)
        version=json.loads(req.get(url="http://aitiyuplus.cn:8091/sports-reform/app/getNewestVersion",headers=self.header).text)
        version=version["version"]
        
        if version!="1.3.9":
            return False
        return True

    def login(self,device):
        if(database.ifExistUserInformation(self.xh)==False):
            logging.info("用户未登录，即将准备登录")
            self.NewLogin(device)
        else:
            logging.info("用户已登录，正在从数据库查询上次登录信息，请稍后")
            self._LoginFromDatabase()
        if self.security_check()!=True:
            logging.critical("安全检查失败！程序即将退出")
            exit()
        
    def _LoginFromDatabase(self):
        data=database.getUserInformation(self.xh)
        self.id=data[0][0]; self.token=data[0][1]; self.device=data[0][2]
        logging.info("从数据库获取访问令牌成功！")
        logging.debug(data)
        self.refreshToken()

    def NewLogin(self,device):
        logging.info("正在获取访问令牌，请稍后")
        self.device=device
        userInfo=self._getUserInfo(self.xh)
        logindata=self._getLoginData(self.xh,self._getEncyPwd(userInfo["password"],self.xh),self.header)
        self.id=logindata["id"]; self.token=logindata["token"]
        user_data=[self.xh,self.id,self.token,self.device]
        logging.info("获取访问令牌成功，正在向数据库服务器添加用户信息")
        database.addUserInformation(user_data)
        logging.info("登录成功")

    def refreshToken(self):
        logging.info("正在刷新访问令牌，请稍后...")
        if(self.token==""):
            logging.critical("错误，数据库Token为空")
            exit()
        TokenHeaders={
            "Accept-Language":"zh-CN,zh;q=0.9",
            "Host": "aitiyuplus.cn:8091",
            "Connection": "Keep-Alive",
            "Accept-Encoding": "gzip",
            "Cookie": "energymanagement="+self.token,
            "User-Agent":"okhttp/4.9.3",
        }
        userInfo=self._getUserInfo(self.xh)
        logindata=self._getLoginData(self.xh,self._getEncyPwd(userInfo["password"],self.xh),TokenHeaders)
        if self.token!=logindata["token"]:
            logging.info("刷新访问令牌成功，正在向数据库服务器添加用户信息")
            self.id=logindata["id"]; self.token=logindata["token"]
            user_data=[self.xh,self.id,self.token,self.device]
            delete_data=[self.xh]
            database.deleteUserInformation(delete_data)
            database.addUserInformation(user_data)
        else:
            logging.info("令牌未改变，无需更新数据库数据")
        logging.info("登录成功")

    def IfLoginInOtherdevice(self,userdata):
        if userdata["uuid"]=="":
            return False
        else:
            return True

    def _getLoginData(self,xh,EncyPwd,headers: dict):
        if headers=={}:
            headers=self.headers
        url1="http://aitiyuplus.cn:8091/basic/xinhai/login"
        newurl=url1+"/"+xh+"/"+EncyPwd
        logindata=req.get(newurl,headers=headers).text
        logindata=json.loads(logindata)
        logging.debug(logindata)
        logindata=logindata["data"]
        return logindata

    def _getUserInfo(self,xh):
        url2="http://aitiyuplus.cn:8091/basic/users/userbyaccount/"+xh
        response=req.get(url=url2,headers=self.header).text
        response=json.loads(response)
        return response
    
    def _getEncyPwd(self,pwd,xh):
        encypwd=self.__encode(str(pwd)+xh)
        return encypwd

    def __encode(self,text):
        md5 = hashlib.md5()
        md5.update(text.encode('utf-8'))
        encoded_text = md5.hexdigest()
        return encoded_text
    
    def __getData(self,num):
        response=[]
        if num == 0:
            logging.info("当前路径模型版本：fuckv1")
            a= fuckv1.Trajectory()
            objs=a.get_trajectory(fuckv1.KeepSpeed(3))
            for obj in objs:
                singledata={}
                singledata["latitude"]=obj.latitude
                singledata["longitude"]=obj.longitude
                response.append(singledata)
        if num == 1:
            logging.info("当前路径模型版本：fuckv2")
            a= fuckv2.Trajectory()
            objs=a.get_trajectory()
            for obj in objs:
                singledata={}
                singledata["latitude"]=obj.latitude
                singledata["longitude"]=obj.longitude
                response.append(singledata)
        if num == 2:
            logging.info("当前路径模型版本：TrajectoryV1")
            a= TrajectoryV1.Trajectory()
            objs=a.get_trajectory()
            for obj in objs:
                singledata={}
                singledata["latitude"]=obj.latitude
                singledata["longitude"]=obj.longitude
                response.append(singledata)
        if num == 3:
            logging.info("当前路径模型版本：NanjubeizhiV1")
            a= NanjubeizhiV1.Nanjubeizhi()
            objs=a.getPointList()
            for obj in objs:
                singledata={}
                singledata["latitude"]=obj[0]
                singledata["longitude"]=obj[1]
                response.append(singledata)

        return response
        

    def run(self):
        logging.info("准备启动跑步")
        if self.token!="" and self.id!="":
            logging.info("初始化用户数据")
            singlerun=Sports.Sport(xh=self.xh,userid=self.id,energymanagement=self.token,appDevice=self.device)
            logging.info("用户数据初始化完毕")
            logging.info("正在生成跑步数据")
            singlerun.start(self.__getData(DATAMODEL))
            logging.info("跑步结束")
            self.disableUserLogger()
            return True
        else:
            logging.ERROR("错误：用户未登录")
            return False
    
    def deboundUUid(self,id,token):
        uuidHeaders={
            "Accept-Language":"zh-CN,zh;q=0.9",
            "Host": "aitiyuplus.cn:8091",
            "Connection": "Keep-Alive",
            "Accept-Encoding": "gzip",
            "Cookie": "energymanagement="+token,
            "User-Agent":"okhttp/4.9.3",
        }
        response=req.get(url="http://aitiyuplus.cn:8091/sports-reform/AddUserController/deboundUUid?userId="+id,headers=uuidHeaders)
        response=json.loads(response)
        if(response["data"]["updateres"]==1):
            return True
        else:
            return False 
        
    def disableUserLogger(self):
        root_logger = logging.getLogger()
        self.file_handler.close()
        root_logger.removeHandler(self.file_handler)
